package com.hjj.homieMatching.utils;

import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import io.minio.errors.MinioException;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * MinIO连接测试工具类
 * 可以在控制台程序中使用，不依赖Spring环境
 */
public class MinIOConnectionTester {

    /**
     * 测试MinIO连接
     * @param endpoint MinIO服务地址
     * @param accessKey 访问密钥
     * @param secretKey 密钥
     * @param bucketName 要测试的桶名称
     * @return 是否连接成功
     */
    public static boolean testConnection(String endpoint, String accessKey, String secretKey, String bucketName) {
        try {
            System.out.println("尝试连接MinIO服务: " + endpoint);
            System.out.println("桶名称: " + bucketName);
            
            // 创建MinIO客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            
            // 检查桶是否存在
            boolean bucketExists = minioClient.bucketExists(
                    BucketExistsArgs.builder().bucket(bucketName).build()
            );
            
            if (bucketExists) {
                System.out.println("存储桶 " + bucketName + " 存在且可访问");
            } else {
                System.out.println("存储桶 " + bucketName + " 不存在");
            }
            
            System.out.println("MinIO连接测试成功！");
            return true;
            
        } catch (MinioException e) {
            System.out.println("MinIO异常: " + e.getMessage());
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            System.out.println("无效的安全凭证: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("IO异常: " + e.getMessage());
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            System.out.println("加密算法不可用: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("未预期的异常: " + e.getMessage());
            e.printStackTrace();
        }
        
        return false;
    }
    
    /**
     * 可以直接运行的主方法
     */
    public static void main(String[] args) {
        // 配置参数，可以从配置文件或命令行参数获取
        String endpoint = "http://127.0.0.1:9000";
        String accessKey = "minioadmin";
        String secretKey = "minioadmin";
        String bucketName = "homie";
        
        boolean success = testConnection(endpoint, accessKey, secretKey, bucketName);
        
        System.out.println("MinIO连接测试结果: " + (success ? "成功" : "失败"));
    }
} 